import datetime
import json

from django.db.models import Q
from rest_framework.permissions import BasePermission
from saas_main import models


class ProjectAllowCreatePersion(BasePermission):
    message = {'ret': 1, "errors": {"project_title": ["项目个数超过限制，请购买后套餐后，重新创建！"]}}

    def has_permission(self, request, view):
        user_right = models.UserRight.objects.filter(user=request.user). \
            filter(Q(end_time__gt=datetime.datetime.now()) | Q(end_time=None)).order_by("-right__category").first()

        right_content = user_right.right
        user_project_count = models.Project.objects.filter(creator=request.user).count()

        if request.method == 'POST':
            user_project_count += 1  # 新增的情况需要+1处理，其余情况相等也可以（即不加一）

        if user_project_count > right_content.project_num:
            return False
        return True


class ProjectDeletePersion(BasePermission):
    message = {'ret': 1, "errors": "项目名错误或当前用户不是项目的创建者！"}

    def has_permission(self, request, view):
        project = models.Project.objects.filter(
            project_title=request.data.get('project_name'),
            creator=request.data.get('user')).first()
        if project:
            return True
        return False


class IsJoinPerssion(BasePermission):
    message = {'ret': 1, "no_fields_error": {"project_title": ["你不是此项目的参与者不能执行此操作！"]}}

    def has_permission(self, request, view):
        project = request.data.get('project') or request.query_params.get('project')
        relation = models.ProjectRelation.objects.filter(user=request.user, project=project).first()
        if relation:
            return True
        return False


class FilePerssion(BasePermission):
    message = {'ret': 1, "errors": '上传文件超出权限空间限制，请额外购买空间！'}

    def has_permission(self, request, view):
        user_right = models.UserRight.objects.filter(user=request.user). \
            filter(Q(end_time__gt=datetime.datetime.now()) | Q(end_time=None)).order_by("-right__category").first()
        right_content = user_right.right
        right_total_space = right_content.project_space * 1024 * 1024
        right_single_space = right_content.single_file_space * 1024 * 1024
        info_list = json.loads(list(request.data.keys())[0])

        project_used_space = request.tracer.project.used_space
        total_size = 0
        for item in info_list:
            total_size += item['size']
            if item['size'] >= right_single_space:
                return False
            if total_size + project_used_space >= right_total_space:
                return False
            if models.FileRepository.objects.filter(name=item['name'], parent=item['parent'], project=item['project'],
                                                    file_type=1).exists():
                self.change_res_message({'ret': 1, "errors": f'上传文件名{item["name"]}有重复，请剔除后重新上传！'})
                return False
        return True

    @classmethod
    def change_res_message(cls, msg):
        cls.message = msg
